package com.xiaoqiu.lease.web.admin.custom.interceptor;

import com.xiaoqiu.lease.common.login.LoginUser;
import com.xiaoqiu.lease.common.login.LoginUserHolder;
import com.xiaoqiu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author xiaoqiu
 * @date 2024/6/9 13:59
 * @description
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            String token = request.getHeader("access-token");

            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            LoginUserHolder.setLoginUser(new LoginUser(userId, username));

            return true;

        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            LoginUserHolder.clear();
        }
}